<template>
	<view class="userpost" :class="[isDark?'dark':'', AppStyle]" :style="{'background-color':isDark?'#1c1c1c':'#f6f6f6','min-height':isDark?'100vh':'auto'}">
		<view class="header" :style="[{height:CustomBar + 'px'}]">
			<view class="cu-bar" :class="isDark?'dark':'bg-white'" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px','background-color':isDark?'#1c1c1c':'#ffffff'}">
				<view class="action" @tap="back">
					<text class="cuIcon-back"></text>
				</view>
				<view class="content text-bold" :style="[{top:StatusBar + 'px'}]">
					{{$t('content.imagetoday.matelibrary')}}
				</view>
				<view class="action" @tap="toUrl('https://www.pexels.com/')">
					<text class="text-blue">Pexels</text>
				</view>
			</view>
		</view>
		<view :style="[{padding:NavBar + 'px 10px 0px 10px'}]"></view>
		<view class="data-box">
			<view class="cu-bar search imagetoday-search" :class="isDark?'dark':'bg-white'" :style="{'background-color':isDark?'#1c1c1c':'#ffffff'}">
				<view class="search-form round">
					<input type="text" placeholder="$t('global.gropekey')" v-model="searchText"/>
					<text class="cuIcon-search" @tap="searchTag()"></text>
				</view>
			</view>
			<view class="no-data" v-if="ImageList.length==0">
				<text class="cuIcon-text"></text>{{$t('common.nodata')}}
			</view>
			<view class="ImageList">
				<view class="ImageList-box"  v-for="(item,index) in ImageList" :key="index">
					<view class="cu-btn bg-blue setImage" v-if="type=='post'" @tap="goPost(item.src.large)">{{$t('common.select')}}</view>
					<image :src="item.src.large2x"  mode="widthFix" @tap="previewImage(item.src.large2x)"></image>
					<view class="image-info">
						<text @tap="toUrl(item.photographer_url)">@{{item.photographer}}</text>
					</view>
				</view>
			</view>
			<view class="load-more" @tap="loadMore" v-if="ImageList.length>0">
				<text>{{moreText}}</text>
			</view>
		</view>
		<!--加载遮罩-->
		<view class="loading" v-if="isLoading==0">
			<view class="loading-main">
				<image src="../../static/loading.gif"></image>
			</view>
		</view>
		<!--加载遮罩结束-->
	</view>
</template>

<script>
	import { localStorage } from '../../js_sdk/mp-storage/mp-storage/index.js'
	import darkModeMixin from '@/utils/darkModeMixin.js'
	export default {
		mixins: [darkModeMixin],
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar:this.StatusBar +  this.CustomBar,
				AppStyle:this.$store.state.AppStyle,
				
				ImageList:[],
				
				searchText:"",
				moreText:$t('common.loadmoretxt'),
				isLoad:0,
				page:1,
				isSearch:0,
				isLoading:0,
				type:"",
			}
		},
		onShow(){
			var that = this;
			// #ifdef APP-PLUS
			
			//plus.navigator.setStatusBarStyle("dark")
			// #endif
			that.getImageList();
		},
		onPullDownRefresh(){
			var that = this;
			var timer = setTimeout(function() {
				that.getImageList();
			}, 1000)
		},
		onReachBottom() {
		    //触底后执行的方法，比如无限加载之类的
			var that = this;
			if(that.isLoad==0){
				that.loadMore();
			}
		},
		onLoad(res) {
			var that = this;
			// #ifdef APP-PLUS || MP
			that.NavBar = that.CustomBar;
			// #endif
			if(res.type){
				that.type = res.type;
			}
		},
		methods: {
			back(){
				uni.navigateBack({
					delta: 1
				});
			},
			reload(){
				var that = this;
				that.getImageList();
			},
			loadMore(){
				var that = this;
				that.moreText = that.$t('global.loading');
				that.isLoad=1;
				that.getImageList(true);
			},
			getImageList(isPage){
				var that = this;
				var page = that.page;
				if(isPage){
					page++;
				}
				var data={
					page:page,
				}
				if(that.searchText!=""){
					data.searchKey = that.searchText;
				}
				that.$Net.request({
					url: that.$API.contentsImage(),
					data:data,
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						uni.stopPullDownRefresh();
						that.isLoad=0;
						if(res.data.photos){
							var list= res.data.photos;
							if(list.length>0){
								if(isPage){
									that.page++;
									that.ImageList = that.ImageList.concat(list);
								}else{
									that.ImageList = list;
								}
							}else{
								that.moreText = that.$t('common.nomoredata');
							}
						}else{
							if(data.msg){
								uni.showToast({
									title: data.msg,
									icon: 'none'
								})
							}else{
								uni.showToast({
									title: that.$t('content.imagetoday.getpicfail'),
									icon: 'none'
								})
							}
						}
						var timer = setTimeout(function() {
							that.isLoading=1;
							clearTimeout('timer')
						}, 300)
					},
					fail: function(res) {
						that.isLoad=0;
						that.moreText = that.$t('common.loadmoretxt');
						uni.stopPullDownRefresh();
						var timer = setTimeout(function() {
							that.isLoading=1;
							clearTimeout('timer')
						}, 300)
					}
				})
			},
			toPost(){
				uni.navigateTo({
					url: '../edit/articlePost'
				});
			},
			toEdit(cid){
				uni.navigateTo({
					url: '../edit/articlePost?type=edit'+'&cid='+cid
				});
			},
			subText(text,num){
				if(text.length < null){
					return text.substring(0,num)+"……"
				}else{
					return text;
				}
			},
			formatDate(datetime) {
				var datetime = new Date(parseInt(datetime * 1000));
				// 获取年月日时分秒值  slice(-2)过滤掉大于10日期前面的0
				var year = datetime.getFullYear(),
					month = ("0" + (datetime.getMonth() + 1)).slice(-2),
					date = ("0" + datetime.getDate()).slice(-2),
					hour = ("0" + datetime.getHours()).slice(-2),
					minute = ("0" + datetime.getMinutes()).slice(-2);
				//second = ("0" + date.getSeconds()).slice(-2);
				// 拼接
				var result = year + "-" + month + "-" + date + " " + hour + ":" + minute;
				// 返回
				return result;
			},
			previewImage(image) {
				var imgArr = [];
				imgArr.push(image);
				//预览图片
				uni.previewImage({
					urls: imgArr,
					current: imgArr[0]
				});
			},
			toUrl(url){
				// #ifdef APP-PLUS
				plus.runtime.openURL(url) 
				// #endif
				// #ifdef H5
				window.open(url)
				// #endif
			},
			searchTag(){
				var that = this;
				that.page=1;
				that.isLoad=1;
				that.ImageList=[];
				that.getImageList(false);
			},
			goPost(url){
				var that = this;
				// #ifdef H5
				uni.showToast({
					title: that.$t('content.imagetoday.plssavepic'),
					icon: 'none'
				})
				// #endif
				// #ifdef APP-PLUS
				var token = "";
				if(localStorage.getItem('userinfo')){
					
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;
					
				}else{
					uni.showToast({
					    title: that.$t('common.plslogin'),
						icon:'none',
						duration: 1000,
						position:'bottom',
					});
					var timer = setTimeout(function() {
						uni.navigateTo({
							url: '/pages/user/login'
						});
						clearTimeout('timer')
					}, 1000)
					return false
				}
				uni.showLoading({
					title: that.$t('common.loadmore')
				});
				uni.downloadFile({//下载
					url: url, //图片下载地址
					success: res => {
						if (res.statusCode === 200) {
							var path = res.tempFilePath;
							const uploadTask = uni.uploadFile({
							url : that.$API.upload(),
							filePath: path,
							name: 'file',
							formData: {
								'token': token
							},
							success: function (uploadFileRes) {
								setTimeout(function () {
								  	uni.hideLoading();
								}, 1000);
								var data = JSON.parse(uploadFileRes.data);
								uni.showToast({
									title: data.msg,
									icon: 'none'
								})
								if(data.code==1){
								   var url = data.data.url;
								   localStorage.setItem('serImage',url);
								   that.back();
								}
								},fail:function(){
									setTimeout(function () {
										uni.hideLoading();
									}, 1000);
								}
							});
						}else{
							setTimeout(function () {
								uni.hideLoading();
							}, 1000);
							uni.showToast({
								title: that.$t('content.imagetoday.picsavefail'),
								icon: 'none',
							});
						}
					}
				});
				// #endif
			},
		}
	}
</script>